package com.xuhj.mysmsmanager.service

import android.app.Service
import android.content.ContentResolver
import android.content.Intent
import android.database.ContentObserver
import android.net.Uri
import android.os.Binder
import android.os.Handler
import android.os.HandlerThread
import android.os.IBinder
import android.util.Log
import com.xuhj.mysmsmanager.MainActivity
import com.xuhj.mysmsmanager.MainActivity.REPORT_SUCCESS_URL
import com.xuhj.mysmsmanager.utils.OkHttpUtil
import okhttp3.*
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.util.*

class ListenerSMSService : Service() {
    //用于在子线程中执行异步操作（这是指短信的查询操作）
    private var handlerThread: HandlerThread? = null
    private var threadHandler: Handler? = null
    private var resultMap = HashMap<String, Int>()

    override fun onBind(intent: Intent?): IBinder {
        contentResolver.registerContentObserver(Uri.parse("content://sms/"), true, contentObserver)
        handlerThread = object : HandlerThread("sms") {
            override fun onLooperPrepared() {
                super.onLooperPrepared()
                threadHandler = Handler(handlerThread?.looper!!)
            }
        }
        handlerThread?.start()
        return Binder()
    }

    override fun onUnbind(intent: Intent?): Boolean {
        contentResolver.unregisterContentObserver(contentObserver)
        return super.onUnbind(intent)
    }

    private val contentObserver = object : ContentObserver(Handler()) {
        override fun onChange(selfChange: Boolean, uris: MutableCollection<Uri>, flags: Int) {
            super.onChange(selfChange, uris, flags)
        }

        override fun onChange(selfChange: Boolean, uri: Uri?) {
            super.onChange(selfChange, uri)
            Log.e("contentObserver", "onChange(selfChange: Boolean, uri: Uri?)")
            uri?.let {
                val value = it.toString()
                Log.e("contentObserver", "uri==$value")
                if (value.startsWith("content://sms/inbox/", true)) {
                    getSMSBody(Uri.parse("content://sms/inbox/"))
                }
            }
        }
    }

    private fun getSMSBody(uri: Uri) {
        threadHandler?.let {
            runnable.uri = uri
            runnable.contentResolver = contentResolver
            it.postDelayed(runnable, 3000)
        }
    }

    private val runnable = object : Runnable {
        var uri: Uri? = null
        var contentResolver: ContentResolver? = null
        override fun run() {
            contentResolver?.let {
                if (uri != null) {
                    val stringBuilder = StringBuilder()
                    val selection = arrayOf("_id", "body", "read", "address")
                    var id:Int? = null; var body = ""
                    var read = ""; var address = "null"
                    val cursor = it.query(
                        uri!!,
                        selection,
                        " date >${System.currentTimeMillis() - 60 * 1000}",
                        null,
                        "date desc"
                    )
                    cursor?.let { cursor ->
                        val idIndex = cursor.getColumnIndex("_id")
                        val bodyIndex = cursor.getColumnIndex("body")
                        val readIndex = cursor.getColumnIndex("read")
                        val addressIndex = cursor.getColumnIndex("address")
                        if (cursor.count > 0) {
                            cursor.moveToFirst()
//                            do {
                            id = cursor.getInt(idIndex)
                            body = cursor.getString(bodyIndex)
                            read = cursor.getString(readIndex)
                            address = cursor.getString(addressIndex)
//                            } while (cursor.moveToNext())
                        }
                    }
                    if (body.contains("OK")) {
                        if (resultMap[address] != null) {
                            resultMap[address] = resultMap[address]!! + 1
                        } else {
                            resultMap[address] = 1
                        }
                        if (MainActivity.templateList != null && resultMap[address]!! >= MainActivity.templateList.size) {
                            val requestBody: RequestBody = RequestBody.create(OkHttpUtil.JSON, "")
                            val request: Request = Request.Builder()
                                .url(REPORT_SUCCESS_URL + address.replace("+", ""))
                                .put(requestBody).build()
                            OkHttpUtil.getHttpClient(60).newCall(request).enqueue(object :
                                Callback {
                                override fun onFailure(call: Call, e: IOException) {
                                }
                                @Throws(IOException::class)
                                override fun onResponse(call: Call, response: Response) {
                                    assert(response.body() != null)
                                    val result = response.body()!!.string()
                                    if (result.isNotEmpty()) {
                                        try {
                                            val jsonObject = JSONObject(result)
                                            val data = jsonObject.getBoolean("data")
                                            if (data) {
                                                Log.e("上报成功", "上报成功:$address")
                                            } else {
                                                Log.e("上报失败", "上报失败:$address")
                                            }
                                        } catch (e: JSONException) {
                                            e.printStackTrace()
                                        }
                                    }
                                }
                            })
                            resultMap.remove(address)
                            Log.e("发送成功", "发送成功:$address")
                        }
                    }
                    stringBuilder.append("id=$id").append("body=$body")
                        .append("read=$read").append("address=$address").append("\n")
                    Log.e("stringBuilder", "stringBuilder==$stringBuilder")
                }
            }
        }
    }
}